# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""This module is used to load image when infer"""
import json
import os

from PIL import Image
from PIL import ImageFile

from mindvision.engine.class_factory import ClassFactory, ModuleType

ImageFile.LOAD_TRUNCATED_IMAGES = True


@ClassFactory.register(ModuleType.DATASET)
class LoadImgFromFile:
    """Load Single Image From File Path For Predict or Infer"""

    def __init__(self, img_file, prefix="id2pic.json"):

        self.prefix = prefix
        self.img_list = list()
        self.id_list = list()
        self.img_dict = dict()

        idx = 0
        if os.path.isdir(img_file):
            for img_name in os.listdir(img_file):
                img_path = os.path.join(img_file, img_name)
                image = Image.open(img_path).convert("RGB")
                self.img_dict[idx] = img_path
                self.img_list.append(image)
                self.id_list.append(idx)
                idx += 1
        else:
            image = Image.open(img_file).convert("RGB")
            self.img_dict[idx] = img_file
            self.img_list.append(image)
            self.id_list.append(idx)

        self.save_img_infos()

    def __getitem__(self, index):
        return self.img_list[index], self.id_list[index]

    def __len__(self):
        return len(self.img_list)

    def save_img_infos(self):
        """Save image information: image id to image name"""
        img_infos = json.dumps(self.img_dict, ensure_ascii=False, indent=4)
        with open(self.prefix, "w+") as f:
            f.write(img_infos)
